package com.taotao.cart.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.cart.bean.User;
import com.taotao.cart.bean.UserThreadLocal;
import com.taotao.cart.service.UserService;
import com.taotao.common.utils.CookieUtils;
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

	@Autowired
	private UserService userService;
	
	/**
	 *购物车判断用户是否登录的拦截器：
	 * 1.获取token，如果token为空，说明未登录，放行
	 * 2.如果token不为空，根据token查询用户，如果用户为空，放行
	 * 3.如果用户不为空，将User对象放入UserThreadLocal,携带到后续的业务处理中，放行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
		if(StringUtils.isNotEmpty(token)){
			//说明token不为空
			User user = this.userService.queryUserByToken(token);
			if(user != null){
				//user已经成功获取到 说明用户已经登录  放入本地线程中
				UserThreadLocal.set(user);
			}
		}
		
		return true;
	}

	//后置方法在视图渲染前执行
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}
	//视图渲染后执行
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//擦除本地线程中的User对象
		UserThreadLocal.set(null);
	}

}